package com.redis.springtest;

import com.redis.springtest.config.RedisConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020-07-27 下午2:14
 */
public class AppRedisBlockList {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class);
        final RedisTemplate redisTemplate = ctx.getBean(RedisTemplate.class);

        final ListOperations listOperations = redisTemplate.opsForList();

        // 清空数据, 可以重复测试
        redisTemplate.delete("list1");
        redisTemplate.delete("list2");

        // 初始化列表list1
        List<String> nodeList = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            nodeList.add("node" + i);
        }

        listOperations.leftPushAll("list1", nodeList);
        // spring使用参数超时时间作为阻塞命令区分,等价于blpop命令,并且可以设置时间参数
        listOperations.leftPop("list1", 1, TimeUnit.SECONDS);
        // spring使用参数超时时间作为阻塞命令区分,等价于blpop命令,并且可以设置时间参数
        listOperations.rightPop("list1", 1, TimeUnit.SECONDS);

        nodeList.clear();

        for (int i = 1; i <= 3; i++) {
            nodeList.add("data" + i);
        }

        listOperations.leftPushAll("list2", nodeList);
        // 相当于rpoplpush命令, 弹出list1最右边节点,插入到list2最左边
        listOperations.rightPopAndLeftPush("list1", "list2");
        // 相当于brpoplpush命令, 注意使用超时参数区分
        listOperations.rightPopAndLeftPush("list1", "list2", 1, TimeUnit.SECONDS);
        // 打印链表数据
        printList(redisTemplate, "list1");
        printList(redisTemplate, "list2");
    }

    private static void printList(RedisTemplate redisTemplate, String key) {
        // 链表长度
        final Long size = redisTemplate.opsForList().size(key);
        // 获取整个链表的值
        final List valueList = redisTemplate.opsForList().range(key, 0, size);
        // 打印
        System.out.println(valueList);
    }
}
